<template>
  <el-container class="calendar-container">
    <el-header class="calendar-header">
      <h2 style="font-weight: bold;">Task Calendar</h2>
      <el-button @click="goToCreateSubtask" type="primary">创建子任务</el-button>
    </el-header>

    <el-main>
      <el-calendar v-model="selectedDate">
        <template #date-cell="{ data }">
          <div class="calendar-cell" :class="{ 'current-month': data.isCurrentMonth }">
            <span class="calendar-date">{{ data.day.split('-')[2] }}</span>
            <!-- 渲染该日期对应的子任务 -->
            <div v-if="groupedSubtasks[data.day]" class="task-list">
              <div
                v-for="subtask in groupedSubtasks[data.day]"
                :key="subtask.id"
                class="task-item"
              >
                <!--<el-tag type="primary">{{ subtask.task.title }}</el-tag>-->
                <div>
                  <el-tag>
                    {{ subtask.assigned_to }} ({{ subtask.start_date }} - {{ subtask.end_date }})
                  </el-tag>
                  <div>{{ subtask.description }}</div>
                </div>
                <el-button @click="showEditSubtaskDialog(subtask)" type="text">编辑</el-button>
                <el-button @click="deleteSubtask(subtask.id)" type="text" style="color: red;">删除</el-button>
              </div>
            </div>
          </div>
        </template>
      </el-calendar>

      <!-- 创建子任务弹窗 -->
      <el-dialog
        :visible.sync="createSubtaskDialogVisible"
        title="创建子任务"
        :append-to-body="true"
      >
        <el-form :model="subtaskForm" label-width="120px">
          <el-form-item label="子任务描述">
            <el-input v-model="subtaskForm.description"></el-input>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="subtaskForm.start_date"
              type="date"
              placeholder="选择开始日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="subtaskForm.end_date"
              type="date"
              placeholder="选择结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="分配给">
            <el-select v-model="subtaskForm.assigned_to" placeholder="选择分配给的成员">
              <el-option
                v-for="user in users"
                :key="user.user_id"
                :label="user.username"
                :value="user.user_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="小组ID">
            <el-input v-model="subtaskForm.group_id" disabled />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="createSubtaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createSubtask">确认创建</el-button>
        </span>
      </el-dialog>

      <!-- 编辑子任务弹窗 -->
      <el-dialog :visible.sync="editSubtaskDialogVisible" title="编辑子任务">
        <el-form :model="subtaskForm" label-width="120px">
          <el-form-item label="子任务描述">
            <el-input v-model="subtaskForm.description"></el-input>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="subtaskForm.start_date"
              type="date"
              placeholder="选择开始日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="subtaskForm.end_date"
              type="date"
              placeholder="选择结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="分配给">
            <el-select v-model="subtaskForm.assigned_to" placeholder="选择分配给的成员">
              <el-option
                v-for="user in users"
                :key="user.user_id"
                :label="user.username"
                :value="user.user_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="小组ID">
            <el-input v-model="groupId" disabled />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editSubtaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editSubtask">确认修改</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { defineComponent, ref, computed, onMounted } from "vue";
import axios from "axios";  // 如果你已配置 axios 实例，确保正确导入
import { useRouter } from "vue-router";

export default defineComponent({
  name: "TaskCalendar",
  setup() {
    const selectedDate = ref(new Date());
    const groupedSubtasks = ref({});  // 按日期分组后的子任务数据
    const users = ref([]); // 存储可选用户列表
    const subtaskForm = ref({
      description: "",
      start_date: "",
      end_date: "",
      assigned_to: null,
      group_id: null  // 用于记录小组ID
    });
    const createSubtaskDialogVisible = ref(false);
    const editSubtaskDialogVisible = ref(false);
    const currentSubtask = ref(null);

    // 当前用户所在小组ID，假设由上层页面传入
    const groupId = ref(null);

    const router = useRouter();

    // 读取 URL 参数（taskId、sysUserId、groupId）
    const taskId = ref(null);
    const sysUserId = ref(null);
    onMounted(() => {
      const params = new URLSearchParams(window.location.search);
      taskId.value = params.get("taskId");
      sysUserId.value = params.get("sysUserId");
      // 假设从用户信息接口中获得组信息后将 groupId 设置到此处
      // 或者从 URL 中传递 groupId（例如：?groupId=xxx）
      groupId.value = params.get("groupId");
      console.log("获取的任务ID:", taskId.value);
      console.log("获取的用户ID:", sysUserId.value);
      console.log("获取的组ID:", groupId.value);
      fetchSubtasks();
      fetchUsers();
    });

    // 获取当前小组的子任务数据，根据 groupId
    const fetchSubtasks = async () => {
      try {
        if (!groupId.value) {
          console.error("groupId 未定义");
          return;
        }
        const response = await axios.get(`http://39.105.217.183:8000/api/subtasks/group/${groupId.value}/`);
        console.log("Fetched subtasks:", response.data);
        // 假设返回的是一个数组
        const data = response.data;
        // 按日期（start_date）分组
        const grouped = {};
        data.forEach((subtask) => {
          const dateKey = subtask.start_date;
          if (!grouped[dateKey]) {
            grouped[dateKey] = [];
          }
          grouped[dateKey].push(subtask);
        });
        groupedSubtasks.value = grouped;
      } catch (error) {
        console.error("Error fetching subtasks:", error.message || error);
      }
    };

    // 获取用户列表（用于下拉框选择分配成员）
    const fetchUsers = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/all-users/");
        users.value = response.data;  // 这里 data 应该是一个数组
      } catch (error) {
        console.error("Error fetching users:", error.message || error);
      }
    };

    // TaskCalendar.vue 中的部分修改
const goToCreateSubtask = () => {
  // 直接跳转到新页面，同时传递必要的参数，如 taskId 和 groupId
  router.push({
    path: "/create-subtask",
    query: {
      taskId: taskId.value,
      groupId: groupId.value,
      sysUserId: sysUserId.value
    }
  });
};


    // 创建子任务
    const createSubtask = async () => {
      try {
        // 前端请求数据中需附带 group_id 字段
        const payload = {
          ...subtaskForm.value,
          group_id: groupId.value,
          task: taskId.value  // 如果需要关联任务
        };
        const response = await axios.post("http://39.105.217.183:8000/api/subtasks/", payload);
        console.log("Subtask created:", response.data);
        await fetchSubtasks(); // 刷新子任务列表
        createSubtaskDialogVisible.value = false;
      } catch (error) {
        console.error("Error creating subtask:", error.message || error);
      }
    };

    // 编辑子任务
    const editSubtask = async () => {
      try {
        const response = await axios.put(`http://39.105.217.183:8000/api/subtasks/${currentSubtask.value.id}/`, {
          ...subtaskForm.value,
          group_id: groupId.value,
          task: taskId.value
        });
        console.log("Subtask updated:", response.data);
        await fetchSubtasks();
        editSubtaskDialogVisible.value = false;
      } catch (error) {
        console.error("Error updating subtask:", error.message || error);
      }
    };

    // 删除子任务
    const deleteSubtask = async (subtaskId) => {
      try {
        await axios.delete(`http://39.105.217.183:8000/api/subtasks/${subtaskId}/`);
        console.log("Subtask deleted:", subtaskId);
        await fetchSubtasks();
      } catch (error) {
        console.error("Error deleting subtask:", error.message || error);
      }
    };

    // 显示创建子任务弹窗
    const showCreateSubtaskDialog = () => {
      console.log("showCreateSubtaskDialog triggered")
      subtaskForm.value = {
        description: "",
        start_date: "",
        end_date: "",
        assigned_to: null,
        group_id: groupId.value
      };
      createSubtaskDialogVisible.value = true;
    };

    // 显示编辑子任务弹窗
    const showEditSubtaskDialog = (subtask) => {
      subtaskForm.value = { ...subtask };
      currentSubtask.value = subtask;
      editSubtaskDialogVisible.value = true;
    };

    return {
      selectedDate,
      groupedSubtasks,
      users,
      subtaskForm,
      createSubtaskDialogVisible,
      editSubtaskDialogVisible,
      showCreateSubtaskDialog,
      showEditSubtaskDialog,
      createSubtask,
      editSubtask,
      deleteSubtask,
      goToCreateSubtask
    };
  }
});
</script>

<style scoped>
/* 保证 el-dialog 能正常显示在 body 上 */
.el-dialog__wrapper {
  z-index: 3000 !important;
}

/* 整体容器 */
.calendar-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 顶部区域 */
.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.calendar-header h2 {
  font-size: 24px;
  font-weight: bold;
}

/* 让日历更紧凑 */
.calendar-cell {
  padding: 10px !important;       /* 默认是10px，可再调 */
  min-height: 80px !important;   /* 默认可能是80px，可再调 */
  position: relative;
  text-align: center;
  border-radius: 5px;
  font-size: 12px;               /* 字体稍微变小 */
}

.current-month {
  color: #333;
}

/* 日期数字 */
.calendar-date {
  display: block;
  font-size: 14px;
  margin-bottom: 4px;
}

/* 任务列表 */
.task-list {
  position: absolute;
  top: 2px;
  left: 3px;
  display: flex;
  flex-direction: column;
  gap: 0px; /* 调小 gap */
}

/* 单个任务条目 */
.task-item {
  font-size: 10px;  /* 文字再小一些 */
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 让按钮也变小 */
.task-item .el-button {
  font-size: 10px;
  padding: 0 1px;
}

/* 弹窗footer对齐 */
.dialog-footer {
  text-align: right;
}
</style>